import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { Tooltip } from 'antd';
import { Node } from '../index';
import { IBgColor } from '../../dictionary';
import type { IStationNodeListType, IEchartParamsType, IFormValue } from '../../type';
import { IPointerType } from '../../type';
import styles from './index.less';

interface IProps {
  /**
   * 价差阻塞信息
   */
  nodePriceSumGridList?: any[];
  /**
   * 配置信息
   */
  nodeStationList?: IStationNodeListType[];
  /**
   * 选择信息
   */
  checkedPriceDiffInfo?: IFormValue;
  /**
   * 展示Echarts图
   */
  onShow?: (params: IEchartParamsType) => void;
}

const NodePriceSumGridList = (props: IProps) => {
  const {
    nodePriceSumGridList = [],
    nodeStationList = [],
    checkedPriceDiffInfo = {},
    onShow,
  } = props;
  const length = nodeStationList?.length;
  const [sectionalData, setSectionalData] = useState<{
    minNum: number;
    maxNum: number;
    list: number[][];
  }>({ minNum: 0, maxNum: 0, list: [] });

  // 对数据进行分段
  const spArr = (arr: number[], num: number) => {
    const newArr = [];
    for (let i = 0; i < arr.length; ) {
      newArr.push(arr.slice(i, (i += num)));
    }
    return newArr;
  };

  const getSectionalData = (
    _nodePriceSumGridList: any[],
  ): {
    minNum: number;
    maxNum: number;
    list: number[][];
  } => {
    let _arr: number[] = [];
    _nodePriceSumGridList.forEach((item) => {
      item.values?.forEach((i) => {
        if (i?.value) {
          _arr.push(i?.value);
        }
      });
    });
    _arr = Array.from(new Set(_arr));
    _arr = _.sortBy(_arr, (o: number) => {
      return o;
    });
    const minNum = _.min(_arr);
    const maxNum = _.max(_arr);
    const _num = Math.ceil(_arr?.length / 20);
    const _list: number[][] = spArr(_arr, _num);
    return {
      minNum,
      maxNum,
      list: _list,
    };
  };

  // 判断数值显示背景的颜色
  const getBgColor = (value: number): number => {
    const { list = [] } = sectionalData;
    let num = 0;
    list.forEach((item: any[], index: number) => {
      const _obj = item.find((i) => {
        return i === value;
      });
      if (_obj) {
        num = index;
      }
    });
    return num;
  };

  //展开Echarts图
  const _onShowEchart = (params: { nodeX?: string; nodeY?: string }) => {
    onShow &&
      onShow({
        blockName: checkedPriceDiffInfo?.blockName,
        date: checkedPriceDiffInfo?.beginDate,
        mode: IPointerType.NINETY_SIX_POINT,
        nodeX: params?.nodeX,
        nodeY: params?.nodeY,
      });
  };

  useEffect(() => {
    const _sectionalData = getSectionalData(nodePriceSumGridList);
    setSectionalData(_sectionalData);
  }, [nodePriceSumGridList]);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.hearderContent}>
          {nodeStationList.map((item, index) => {
            return (
              <div
                className={styles.nodeStation}
                style={{ width: `calc(100% / ${length})` }}
                key={`${item.nodeId}-${index}`}
              >
                <Node nodeInfo={item} style={{ justifyContent: 'center' }} />
              </div>
            );
          })}
        </div>
      </div>
      <div className={styles.bottom}>
        <div className={styles.left}>
          <div className={styles.leftContent}>
            {nodeStationList.map((item, index) => {
              return (
                <div
                  className={styles.nodeStation}
                  key={`${item.nodeId}-${index}`}
                  style={{ height: `calc(100% / ${length})` }}
                >
                  <Node nodeInfo={item} style={{ justifyContent: 'flex-end' }} />
                </div>
              );
            })}
          </div>
        </div>
        <div className={styles.right}>
          {nodePriceSumGridList.map((item, index) => {
            const _nodeId = nodeStationList[index]?.nodeId;
            const _item = nodePriceSumGridList.find((i) => i?.nodeId === _nodeId);
            const { values = [] } = _item || {};
            return _item ? (
              <div
                className={styles.nodePriceSumGrid}
                key={`${item?.nodeId}-${index}`}
                style={{ height: `calc(100% / ${length})`, width: '100%' }}
              >
                {values.map((i: any, j: number) => {
                  const _nodeIdi = nodeStationList[j]?.nodeId;
                  const _itemi = values.find((k: any) => k?.nodeId === _nodeIdi);
                  const _num: number = getBgColor(_itemi?.value ?? 0);
                  return _itemi ? (
                    <Tooltip
                      placement="topLeft"
                      title={i?.value || ''}
                      key={`${item?.nodeId}-${index}-${i?.nodeId}-${index}-${j}`}
                    >
                      <div
                        className={styles.nodePriceSum}
                        style={{
                          width: `calc(100% / ${length})`,
                          height: '100%',
                          backgroundColor:
                            item?.nodeId === i?.nodeId
                              ? 'var(--bd-primary-a50)'
                              : (_itemi?.value ?? 0) === 0
                              ? 'var(--bd-primary-a20)'
                              : IBgColor[_num]?.bgColor || 'var(--bd-primary-a20)',
                          color:
                            (_itemi?.value ?? 0) === 0
                              ? 'var(--bd-primary-a20)'
                              : IBgColor[_num]?.color || '#161A1D',
                        }}
                        onClick={() =>
                          _onShowEchart({ nodeX: _itemi?.nodeId, nodeY: _item?.nodeId })
                        }
                        key={`${item?.nodeId}-${index}-${i?.nodeId}-${index}-${j}`}
                      >
                        {_itemi?.value || ''}
                      </div>
                    </Tooltip>
                  ) : null;
                })}
              </div>
            ) : null;
          })}
        </div>
      </div>
    </div>
  );
};

export default NodePriceSumGridList;
